<?php
/**
 * @file indigo/framework/classes/Database.php
 * Contains definition for the Database class and the exceptions that it throws (InvalidUserException, InvalidDatabaseTypeException, InvalidDatabaseNameException)
 * Imports the PDO and Exception classes from the global namespace
 */
  namespace indigo\framework;
  use PDO;
  use Exception;
  
 /**
  * @class InvalidUserException
  * Thrown when MySQL returns the 1045 error code, indicating either the username or the password is incorrect
  */
  class InvalidUserException extends Exception {}

 /**
  * @class InvalidDatabaseNameException
  * Thrown when MySQL returns the 1049 error code, indicating that the indicated database could not be found
  */
  class InvalidDatabaseNameException extends Exception {}

 /**
  * @class InvalidDatabaseTypeException
  * Thrown when the database type provided is invalid or currently not supported
  */
  class InvalidDatabaseTypeException extends Exception {}
  
 /**
  * @class Database
  *
  * PDO wrapper
  *
  * The database class that wraps the constructor to load database connection details from the Config class to provide error handling
  *   for database PDO errors
  */
  class Database extends PDO
  {
   /**
    * PDO constructor wrapper
    *
    * Instantiates the PDO class using values loaded from the Config class and tries to manage MySQL connection errors if a PDOException
    *   is thrown
    *
    * @param $config An instance of the Config class
    *
    * @exception InvalidUserException Thrown when MySQL returns the 1045 error code, indicating either the username or the password is incorrect
    * @exception InvalidDatabaseNameException Thrown when MySQL returns the 1049 error code, indicating that the indicated database could not be found
    * @exception InvalidDatabaseTypeException Thrown when the database type provided is invalid or currently not supported
    * @exception PDOException The rethrown PDOException that may have been thrown by the parent constructor and does not fall in the above exceptions
    */
    function __construct(Config $config)
    {
      $dsn = NULL;
      switch ($config->get('db_type'))
      {
        case 'mysql':
          $dsn = 'mysql:host=' . $config->get('db_host') . ';dbname=' . $config->get('db_name');
          break;
        default:
          throw new InvalidDatabaseTypeException('Invalid / Unsupported database type');
      }

      try {
        parent::__construct($dsn, $config->get('db_user'), $config->get('db_pass'));
      } catch (Exception $e) {
        switch ($e->getCode())
        {
          case 1045:
            throw new InvalidUserException('Invalid database user');
            break;
          case 1049:
            throw new InvalidDatabaseNameException('Invalid database name');
            break;
          default:
            throw $e;
        }
      }
    }
  }